package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ChenYongHao
 * @date 2023/4/24 10:35
 * @desc 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        ////先设置用户id,指定当前是哪个用户的购物车数据  因为前端没有传这个id给我们,但是这个id又非常重要（数据库这个字段不能为null）,
        //    // 所以要想办法获取到,我们在用户登录的时候就已经保存了用户的id
        Long userid = BaseContext.getCurrentId();
        shoppingCart.setUserId(userid);

        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userid);
        if (dishId == null) {
            //添加到购物车是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        } else {
            //添加到购物车是菜品
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        }
        //查询当前菜品是否或者是套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart shoppingCartExist = shoppingCartService.getOne(queryWrapper);

        if (shoppingCartExist == null) {
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            shoppingCartExist = shoppingCart;
        } else {
            //已存在情况 累加
            //如果已经存在,就在原来的数量基础上加一
            Integer number = shoppingCartExist.getNumber();
            shoppingCartExist.setNumber(number + 1);
            shoppingCartService.updateById(shoppingCartExist);

        }
        return R.success(shoppingCartExist);
    }

    /**
     * 获取购物车列表
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> getShoppingCartList() {
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(ShoppingCart::getCreateTime);
//        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        return R.success(shoppingCartService.list(wrapper));
    }

    //http://localhost:8080/shoppingCart/clean

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }

    //http://localhost:8080/shoppingCart/sub

    /**
     * 客户端的套餐或者是菜品数量减少设置
     * 没必要设置返回值
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    @Transactional
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //数量减少的菜品
        if (dishId != null) {
            //查询菜品对象
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
            //这里必须要加两个条件，否则会出现用户互相修改对方与自己购物车中相同套餐或者是菜品的数量
            queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
            ShoppingCart shoppingCartDish = shoppingCartService.getOne(queryWrapper);
            shoppingCartDish.setNumber(shoppingCartDish.getNumber()-1);
            Integer number = shoppingCartDish.getNumber();
            if (number > 0){
                //对数据进行更新操作
                shoppingCartService.updateById(shoppingCartDish);
            }else if(number == 0){
                //如果购物车的菜品数量减为0，那么就把菜品从购物车删除
                shoppingCartService.removeById(shoppingCartDish.getId());
            }else if (number < 0){
                return R.error("操作异常");
            }
            return R.success(shoppingCartDish);
        }

        Long setmealId = shoppingCart.getSetmealId();
        if (setmealId != null){
            //代表是套餐数量减少
            queryWrapper.eq(ShoppingCart::getSetmealId,setmealId).eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
            ShoppingCart cart2 = shoppingCartService.getOne(queryWrapper);
            cart2.setNumber(cart2.getNumber()-1);
            Integer LatestNumber = cart2.getNumber();
            if (LatestNumber > 0){
                //对数据进行更新操作
                shoppingCartService.updateById(cart2);
            }else if(LatestNumber == 0){
                //如果购物车的套餐数量减为0，那么就把套餐从购物车删除
                shoppingCartService.removeById(cart2.getId());
            }else if (LatestNumber < 0){
                return R.error("操作异常");
            }
            return R.success(cart2);
        }
        //如果两个大if判断都进不去
        return R.error("操作异常");
    }

}
